import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useFileDataStore } from './fileData'

export interface Workspace {
  id: string
  name: string
  description: string
  type: string
  status: 'active' | 'inactive'
  createTime: string
  filePath?: string // 解压后的文件路径
  extractedData?: string // 解压后的文件内容
  stats: {
    logFiles: number
    analysisTasks: number
  }
}

export const useWorkspaceStore = defineStore('workspace', () => {
  // 状态 - 从本地存储恢复工作区数据
  const workspaces = ref<Workspace[]>([])

  // 从本地存储恢复当前工作区ID
  const currentWorkspaceId = ref(localStorage.getItem('currentWorkspaceId') || '')

  // 初始化工作区数据
  async function initializeWorkspaces() {
    try {
      const storedWorkspaces = localStorage.getItem('workspaces')
      if (storedWorkspaces) {
        const parsedWorkspaces = JSON.parse(storedWorkspaces)
        
        // 从fileData store恢复大文件数据
        const fileDataStore = useFileDataStore()
        await fileDataStore.initializeFromStorage()
        
        // 为每个工作区恢复完整数据
        const restoredWorkspaces = await Promise.all(
          parsedWorkspaces.map(async (workspace: Workspace) => {
            // 如果workspace没有extractedData，尝试从fileData store恢复
            if (!workspace.extractedData) {
              const fileData = fileDataStore.getFileData(workspace.id)
              if (fileData) {
                console.log(`从fileData store恢复工作区 ${workspace.id} 的大文件数据，长度: ${fileData.length}`)
                return {
                  ...workspace,
                  extractedData: fileData
                }
              }
            }
            return workspace
          })
        )
        
        workspaces.value = restoredWorkspaces
        console.log('从localStorage和fileData store恢复工作区数据:', restoredWorkspaces.length, '个工作区')
        
        // 验证数据恢复情况
        for (const workspace of restoredWorkspaces) {
          if (workspace.extractedData) {
            console.log(`工作区 ${workspace.id} 数据恢复成功，长度: ${workspace.extractedData.length}`)
          } else {
            console.warn(`工作区 ${workspace.id} 数据恢复失败，没有extractedData`)
          }
        }
      }
    } catch (error) {
      console.error('恢复工作区数据失败:', error)
      workspaces.value = []
    }
  }

  // 计算属性
  const currentWorkspace = computed(() => {
    return workspaces.value.find(w => w.id === currentWorkspaceId.value)
  })

  const workspaceOptions = computed(() => {
    return workspaces.value.map(w => ({
      label: w.name,
      value: w.id
    }))
  })

  // 方法
  function setCurrentWorkspace(workspaceId: string) {
    currentWorkspaceId.value = workspaceId
    // 保存到本地存储
    localStorage.setItem('currentWorkspaceId', workspaceId)
    // 可以在这里添加加载工作区数据的逻辑
    console.log('切换到工作区:', workspaceId)
  }

  function createWorkspace(workspaceData: Omit<Workspace, 'id' | 'createTime' | 'stats'>) {
    const newId = `workspace-${Date.now()}`
    const workspace: Workspace = {
      id: newId,
      ...workspaceData,
      createTime: new Date().toISOString().split('T')[0],
      stats: {
        logFiles: 0,
        analysisTasks: 0
      }
    }
    
    workspaces.value.push(workspace)
    
    // 如果有大文件数据，保存到fileData store
    if (workspace.extractedData && workspace.extractedData.length >= 1024 * 1024) {
      const fileDataStore = useFileDataStore()
      fileDataStore.setFileData(newId, workspace.extractedData)
      console.log(`大文件数据已保存到fileData store，工作区ID: ${newId}，大小: ${(workspace.extractedData.length / 1024 / 1024).toFixed(2)}MB`)
    }
    
    // 保存到localStorage（不包含大文件数据）
    const workspacesForStorage = workspaces.value.map(w => ({
      ...w,
      // 大文件数据不保存到localStorage，只保存到fileData store
      extractedData: (w.extractedData && w.extractedData.length >= 1024 * 1024) ? undefined : w.extractedData
    }))
    localStorage.setItem('workspaces', JSON.stringify(workspacesForStorage))
    console.log('工作区数据已保存到localStorage，数量:', workspacesForStorage.length)
    
    // 如果是第一个工作区，自动设置为当前工作区
    if (workspaces.value.length === 1) {
      currentWorkspaceId.value = newId
      localStorage.setItem('currentWorkspaceId', newId)
    }
    
    return workspace
  }

  function deleteWorkspace(workspaceId: string) {
    const index = workspaces.value.findIndex(w => w.id === workspaceId)
    if (index > -1) {
      const workspace = workspaces.value[index]
      
      // 如果工作区有大文件数据，从fileData store中删除
      if (workspace.extractedData && workspace.extractedData.length >= 1024 * 1024) {
        const fileDataStore = useFileDataStore()
        fileDataStore.removeFileData(workspaceId)
        console.log(`大文件数据已从fileData store删除，工作区ID: ${workspaceId}`)
      }
      
      workspaces.value.splice(index, 1)
      
      // 保存到localStorage（不包含大文件数据）
      const workspacesForStorage = workspaces.value.map(w => ({
        ...w,
        // 大文件数据不保存到localStorage，只保存到fileData store
        extractedData: (w.extractedData && w.extractedData.length >= 1024 * 1024) ? undefined : w.extractedData
      }))
      localStorage.setItem('workspaces', JSON.stringify(workspacesForStorage))
      console.log('工作区数据已保存到localStorage，数量:', workspacesForStorage.length)
      
      // 如果删除的是当前工作区，切换到第一个工作区或清空
      if (currentWorkspaceId.value === workspaceId) {
        currentWorkspaceId.value = workspaces.value[0]?.id || ''
        // 更新本地存储
        if (currentWorkspaceId.value) {
          localStorage.setItem('currentWorkspaceId', currentWorkspaceId.value)
        } else {
          localStorage.removeItem('currentWorkspaceId')
        }
      }
    }
  }

  function updateWorkspaceStats(workspaceId: string, stats: Partial<Workspace['stats']>) {
    const workspace = workspaces.value.find(w => w.id === workspaceId)
    if (workspace) {
      workspace.stats = { ...workspace.stats, ...stats }
    }
  }

  // 更新工作区数据（包括大文件数据）
  async function updateWorkspaceData(workspaceId: string, updates: Partial<Workspace>) {
    const workspace = workspaces.value.find(w => w.id === workspaceId)
    if (workspace) {
      // 更新基本信息
      Object.assign(workspace, updates)
      
      // 如果更新了extractedData，需要同步到fileData store
      if (updates.extractedData !== undefined) {
        const fileDataStore = useFileDataStore()
        if (updates.extractedData && updates.extractedData.length >= 1024 * 1024) {
          // 大文件数据保存到fileData store
          await fileDataStore.setFileData(workspaceId, updates.extractedData)
          console.log(`大文件数据已更新到fileData store，工作区ID: ${workspaceId}，大小: ${(updates.extractedData.length / 1024 / 1024).toFixed(2)}MB`)
        } else if (updates.extractedData && updates.extractedData.length < 1024 * 1024) {
          // 小文件数据从fileData store中删除（如果存在）
          if (fileDataStore.hasFileData(workspaceId)) {
            await fileDataStore.removeFileData(workspaceId)
            console.log(`小文件数据已从fileData store删除，工作区ID: ${workspaceId}`)
          }
        }
      }
      
      // 保存到localStorage（不包含大文件数据）
      const workspacesForStorage = workspaces.value.map(w => ({
        ...w,
        // 大文件数据不保存到localStorage，只保存到fileData store
        extractedData: (w.extractedData && w.extractedData.length >= 1024 * 1024) ? undefined : w.extractedData
      }))
      localStorage.setItem('workspaces', JSON.stringify(workspacesForStorage))
      console.log('工作区数据已保存到localStorage，数量:', workspacesForStorage.length)
    }
  }

  return {
    // 状态
    workspaces,
    currentWorkspaceId,
    
    // 计算属性
    currentWorkspace,
    workspaceOptions,
    
    // 方法
    initializeWorkspaces,
    setCurrentWorkspace,
    createWorkspace,
    deleteWorkspace,
    updateWorkspaceStats,
    updateWorkspaceData
  }
}) 